/*
@Copyright:LintCode
@Author:   tjyemail
@Problem:  http://www.lintcode.com/problem/validate-binary-search-tree
@Language: C++
@Datetime: 16-02-09 08:50
*/

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    bool isValidBSTCore(TreeNode *root,int &val,bool &flag){
        if (root==NULL)
            return true;
        bool left = isValidBSTCore(root->left,val,flag);
        if (!left)
            return false;
        if (flag && root->val <= val)
            return false;
        else
            flag= true;
        val = root->val;
        bool right = isValidBSTCore(root->right,val,flag);
        if (!right)
            return false;
        return true;
    }
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    bool isValidBST(TreeNode *root) {
        // write your code here
        int val = 0;
        bool flag = false;
        return isValidBSTCore(root,val,flag);
    }
};